package org.jsola.hr.web;

import org.jsola.admin.entity.SiteDO;
import org.jsola.common.StrKit;
import org.jsola.contract.entity.ContractDO;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.CacheKeyKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.CustomDTO;
import org.jsola.hr.dto.CustomTemplateAddDTO;
import org.jsola.hr.dto.CustomTemplateUpdateDTO;
import org.jsola.hr.entity.CompanyDO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.provider.IAdminProviderService;
import org.jsola.hr.query.CustomTemplateQuery;
import org.jsola.hr.service.ICustomTemplateService;
import org.jsola.hr.vo.CustomFieldValueVO;
import org.jsola.hr.vo.CustomTemplateListVO;
import org.jsola.hr.vo.CustomTemplateVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 自定义模板
 *
 * @author zhr
 */
@RestController("hrCustomTemplateController")
@RequestMapping(HrConstants.API_PATH + "/v1/customTemplates")
public class CustomTemplateController implements ICustomTemplateControllerAPI {

    @Autowired
    private ICustomTemplateService customTemplateService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IAdminProviderService adminProviderService;

    @Override
    @PostMapping
    public Result<CustomTemplateVO> save(@Valid @RequestBody CustomTemplateAddDTO customTemplateAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增自定义模板权限校验

        return Result.success(
                customTemplateService.save(customTemplateAddDTO, tokenUser)
        );
    }

    @Override
    @PostMapping("/saveTemplate")
    public Result<CustomTemplateVO> saveTemplate(@Valid @RequestBody CustomTemplateAddDTO customTemplateAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增自定义模板权限校验

        return Result.success(
                customTemplateService.saveTemplate(customTemplateAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody CustomTemplateUpdateDTO customTemplateUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改自定义模板权限校验

        int count = customTemplateService.update(customTemplateUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @PutMapping("/update2")
    public Result<Integer> update2(@Valid @RequestBody CustomTemplateUpdateDTO customTemplateUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改自定义模板权限校验

        int count = customTemplateService.update2(customTemplateUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @DeleteMapping(value = "/{customTemplateId}")
    public Result<Integer> delete(@PathVariable String customTemplateId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除自定义模板权限校验

        int count = customTemplateService.deleteById(tokenUser, customTemplateId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] customTemplateIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除自定义模板权限校验

        int count = customTemplateService.deleteByIds(tokenUser, customTemplateIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{customTemplateId}")
    public Result<CustomTemplateVO> findById(@PathVariable String customTemplateId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看自定义模板权限校验

        return Result.success(
                customTemplateService.selectById(customTemplateId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<CustomTemplateListVO>> listAll(@Valid CustomTemplateQuery customTemplateQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看自定义模板权限校验

        return Result.success(
                customTemplateService.select(customTemplateQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<CustomTemplateListVO>> page(@Valid CustomTemplateQuery customTemplateQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                customTemplateService.selectPage(customTemplateQuery, tokenUser)
        );
    }

    @Override
    @PostMapping("/open")
    public Result<Integer> open(@Valid @RequestBody CustomDTO customDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                customTemplateService.open(customDTO.getCompanyId(), customDTO.getTemplateId(), tokenUser)
        );
    }

    @Override
    @PostMapping("/open2")
    public Result<Integer> open2(@Valid @RequestBody CustomDTO customDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                customTemplateService.open2(customDTO.getCompanyId(), customDTO.getTemplateId(), tokenUser)
        );
    }

    @Override
    @PostMapping("/asyncIssueTemplate")
    public Result<Integer> asyncIssueTemplate(@Valid @RequestBody CustomDTO customDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        List<String> companyIdList = customDTO.getCompanyIdList();
        if (CollectionUtils.isEmpty(companyIdList)) {
            throw new ParamException("请选择需要下发的用工单位");
        }
        String key = CacheKeyKit.getIssueTemplate(tokenUser.getSiteId());
        RLock lock = redissonClient.getLock(key);
        if (lock.isLocked()) {
            throw new HrException("正在下发入职模板，请稍后操作");
        }
        //companyId 只指用工单位id, enterpriseSignDTO.getCompanyId() 是合同模板印章中认证的公司信息
        customTemplateService.asyncIssueTemplate(customDTO, tokenUser);
        return Result.success();
    }

    @Override
    @PostMapping("/issueTemplate")
    public Result<Integer> issueTemplate(@Valid @RequestBody CustomDTO customDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                customTemplateService.issueTemplate(customDTO, tokenUser)
        );
    }

    @Override
    @PostMapping("/issueTemplate2")
    public Result<Integer> issueTemplate2(@Valid @RequestBody CustomDTO customDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        customTemplateService.asyncIssueTemplate2(customDTO, tokenUser);
        return Result.success(1
        );
    }

    @Override
    @GetMapping("/selectOpenTemplate")
    public Result<CustomTemplateVO> selectOpenTemplate(@RequestParam("moduleCode") String moduleCode,
                                                       String companyId,
                                                       String siteId) {
        TokenUser tokenUser = new TokenUser();
        // 小程序查询，构建tokenUser
        if (StrKit.isNotEmpty(siteId)) {
            tokenUser.setSiteId(siteId);
        } else {
            tokenUser = UserContext.getUser();
        }
        // todo 查看项目权限校验

        return Result.success(
                customTemplateService.selectOpenTemplate(moduleCode, companyId, tokenUser)
        );
    }

    @Override
    @GetMapping("/selectOpenTemplate2")
    public Result<CustomTemplateVO> selectOpenTemplate2(@RequestParam("moduleCode") String moduleCode,
                                                       String companyId,
                                                       String siteId) {
        TokenUser tokenUser = new TokenUser();
        // 小程序查询，构建tokenUser
        if (StrKit.isNotEmpty(siteId)) {
            tokenUser.setSiteId(siteId);
        } else {
            tokenUser = UserContext.getUser();
        }
        // todo 查看项目权限校验

        return Result.success(
                customTemplateService.selectOpenTemplate2(moduleCode, companyId, tokenUser)
        );
    }

    @Override
    @GetMapping("/selectOpenTemplate3")
    public Result<CustomTemplateVO> selectOpenTemplate3(@RequestParam("moduleCode") String moduleCode,
                                                       String companyId,
                                                       String siteId) {
        TokenUser tokenUser = new TokenUser();
        // 小程序查询，构建tokenUser
        if (StrKit.isNotEmpty(siteId)) {
            tokenUser.setSiteId(siteId);
        } else {
            tokenUser = UserContext.getUser();
        }
        // todo 查看项目权限校验

        return Result.success(
                customTemplateService.selectOpenTemplate3(moduleCode, companyId, tokenUser)
        );
    }

    @Override
    @GetMapping("/getCheckInField")
    public Result<CustomFieldValueVO> getCheckInField(@RequestParam("checkInId") String checkInId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                customTemplateService.getCheckInField(checkInId, tokenUser)
        );
    }

    @Override
    @GetMapping("/getEmpField")
    public Result<CustomFieldValueVO> getEmpField(@RequestParam("empId") String empId,
                                                  @RequestParam("moduleType") String moduleType) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                customTemplateService.getEmpField(empId, moduleType, tokenUser)
        );
    }

    /**
     * 修复租户级默认模板(没有就创建)
     *
     */
    @PostMapping("/repairSiteDefault")
    public Result<CustomFieldValueVO> repairSiteDefault() {

        Map<String, SiteDO> siteMap = adminProviderService.selectSiteMap();
        for (String siteId : siteMap.keySet()) {
            TokenUser tokenUser = new TokenUser("repairSiteDefault", siteId);
            customTemplateService.saveDefaultBySite(tokenUser);
        }
        return Result.success(
        );
    }

    /**
     * 下发租户的可选自定义信息到所有用工单位
     * @return 无
     */
    @PostMapping("/issuedAllAdditionalFields")
    public Result<Integer> issuedAllAdditionalFields() {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        customTemplateService.issuedAllAdditionalFields();
        return Result.success(
        );
    }

    /**
     * 下发租户的默认模板到所有用工单位 (前提是用工单位没有自己创建默认模板)
     * @return 无
     */
    @PostMapping("/issuedAllAdditionalFields2")
    public Result<Integer> issuedAllAdditionalFields2() {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        customTemplateService.issuedAllAdditionalFields2();
        return Result.success(
        );
    }

    /**
     * 下发指定租户的默认模板到用工单位 (没有指定用工单位 则下发所有用工单位 强制更新)
     * @return 无
     */
    @PostMapping("/issuedAllAdditionalFields3/{templateId}")
    public Result<Integer> issuedAllAdditionalFields3(@PathVariable String templateId, @RequestBody String[] companyIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        customTemplateService.issuedAllAdditionalFields3(templateId, Arrays.asList(companyIds), tokenUser);
        return Result.success(
        );
    }

}

